﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Rhombus.Data;
using System.Linq.Expressions;
using System.Globalization;

namespace RhombusWebMVC.Models
{
	public class WorkItemRepository : IWorkItemRepository<Guid, WorkItemViewModel>
	{
		private RhombusEntities m_context = new RhombusEntities();

		#region IWorkItemRepository Members

		public WorkItemViewModel GetWorkItem(Guid id)
		{
			var model = GetWorkItemsInternal().First(w => w.ID == id);

			return model;
		}

		public IEnumerable<WorkItemViewModel> GetWorkItems()
		{
			var model = GetWorkItemsInternal().ToList();

			return model;
		}

		public Guid CreateWorkItem(WorkItemViewModel model, string user)
		{
			var workItem = new WorkItem();

			workItem.WorkItemPK = Guid.NewGuid();
			workItem.Summary = model.Summary;

			var history = new WorkItemHistory();
			history.WorkItemHistoryPK = Guid.NewGuid();
			history.CreatedDate = DateTime.Now;
			history.CreatedByUser = user;
			history.IsSystem = true;
			history.Text = String.Format(CultureInfo.CurrentUICulture, Properties.Resources.WorkItem_History_Created, history.CreatedDate, history.CreatedByUser);

			workItem.WorkItemHistories.Add(history);

			m_context.AddToWorkItems(workItem);
			m_context.SaveChanges();

			return workItem.WorkItemPK;
		}

		public void EditWorkItem(Guid id, WorkItemViewModel model, string user)
		{
			var workItem = m_context.WorkItems.First(w => w.WorkItemPK == id);

			workItem.Summary = model.Summary;

			var history = new WorkItemHistory();
			history.WorkItemHistoryPK = Guid.NewGuid();
			history.CreatedDate = DateTime.Now;
			history.CreatedByUser = user;
			history.IsSystem = true;
			history.Text = String.Format(CultureInfo.CurrentUICulture, Properties.Resources.WorkItem_History_Edited, history.CreatedDate, history.CreatedByUser);

			workItem.WorkItemHistories.Add(history);

			m_context.SaveChanges();
		}

		#endregion

		private IQueryable<WorkItemViewModel> GetWorkItemsInternal()
		{
			return m_context.WorkItems
							.Include("WorkItemHistories")
							.Select(w => new WorkItemViewModel
							{
								ID = w.WorkItemPK,
								Summary = w.Summary,
								History = w.WorkItemHistories.OrderByDescending(h => h.CreatedDate).Select(h => new WorkItemHistoryViewModel
								{
									PrimaryKey = h.WorkItemHistoryPK,
									WorkItemFK = w.WorkItemPK,
									Text = h.Text,
									IsSystem = h.IsSystem,
									IsPublic = h.IsPublic,
									CreatedDate = h.CreatedDate,
									CreatedByUser = h.CreatedByUser
								})
							});
		}
	}
}